<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>人工管理</title>
    <!-- 引入其它组件 -->
    <!-- 引入 layui -->
    <link rel="stylesheet" href="/layui/css/layui.css">
    <link rel="stylesheet" href="/css/app.css">
</head>

<body>
    <div class="container">
        <div class="tab-toolbar" style="text-align: center;">
            <button class="layui-btn layui-btn-normal" id="btn-add">
                <i class="layui-icon">&#xe654;</i>添加
            </button>
            <button class="layui-btn layui-btn-normal" id="btn-save">
                <i class="layui-icon">&#xe605;</i>保存
            </button>
            <span id="save-status" style="margin-left: 15px; color: #666; display: none;">
                <span class="status-indicator status-saved"></span>已保存
            </span>
        </div>

        <div class="table-container">
            <div class="table-wrapper">
                <table class="layui-table" id="table3a">
                </table>
            </div>
        </div>
    </div>
    <script type="text/html" id="table3a-bar">
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="delete">删除</a>
    </script>

    <script src="/js/config/api.js"></script>
    <script src="/js/http.js"></script>
    <script src="/layui/layui.js"></script>
    <script src="/js/utils.js"></script>

    <script>
        layui.use(['table', 'layer', 'form'], function () {
            var table = layui.table;
            var layer = layui.layer;
            var form = layui.form;
            var $ = layui.$;
            var bsm_utils = layui.bsm_utils;

            // 全局数据存储
            var tableData = [];
            var designCode = getUrlParam("design_code");
            var designType = parseInt(getUrlParam("design_type"));
            var hasUnsavedChanges = false;
            var originalDataHash = ""; // 用于比较数据是否改变

            // 表格渲染后调整
            table.on('done(table3a)', function () {
                setTimeout(function () {
                    bsm_utils.notifyParentResize({
                        minWidth: 800,
                        minHeight: 600
                    });
                }, 300);
                // layui.tips({
                //     elem: obj.elem.find('.layui-table-cell'),
                //     type: 'tips',
                //     tips: [1, '#393D49']
                // });

            });

            // 初始化表格
            function initTable() {
                table.render({
                    elem: '#table3a',
                    data: tableData,
                    cellExpandedMode: 'tips',
                    cols: [
                        [
                            { type: 'numbers', title: '序号', width: "60", align: 'center', rowspan: 2 },
                            { title: '定额编号', field: 'norm_code', width: "100", align: 'center', rowspan: 2, totalRowText: '合计' },
                            { title: '项目名称', field: 'norm_name', width: "300", align: 'left', rowspan: 2 },
                            { title: '单位', field: 'norm_unit', width: "80", align: 'center', rowspan: 2 },
                            { title: '数量', field: 'quantity', edit: 'text', width: "80", align: 'right', rowspan: 2 },
                            { title: '单位定额（工日）', align: 'center', colspan: 2, rowspan: 1 },
                            { title: '合计定额（工日）', align: 'center', colspan: 2, rowspan: 1 },
                            { title: '调整后（工日）', align: 'center', colspan: 2, rowspan: 1, },
                            { title: '备注', field: 'remark', width: "160", align: 'left', rowspan: 2 },
                            { title: '操作', width: "60", align: 'center', toolbar: '#table3a-bar', rowspan: 2 },
                        ],
                        [
                            { title: '技工', field: 'norm_mechanic', templet: function (d) { return Number(d.norm_mechanic).toFixed(2); }, width: "70", align: 'right' },
                            { title: '普工', field: 'norm_general', templet: function (d) { return Number(d.norm_general).toFixed(2); }, width: "70", align: 'right' },
                            { title: '技工', field: 'mechanics', templet: function (d) { return Number(d.mechanics).toFixed(2); }, width: "70", align: 'right', totalRow: true },
                            { title: '普工', field: 'generals', templet: function (d) { return Number(d.generals).toFixed(2); }, width: "70", align: 'right', totalRow: true },
                            { title: '技工', field: 'converted_mechanics', templet: function (d) { return Number(d.converted_mechanics).toFixed(2); }, width: "70", align: 'right', totalRow: true },
                            { title: '普工', field: 'converted_generals', templet: function (d) { return Number(d.converted_generals).toFixed(2); }, width: "70", align: 'right', totalRow: true },
                        ]
                    ],
                    totalRow: true,
                    done: function (res, curr, count) {
                        bindTableEvents();
                        updateSaveStatus();

                        // 双击行事件
                        $('.layui-table-body tr').on('dblclick', function () {
                            var index = $(this).data('index');
                            var rowData = table.cache['table3a'][index]; // 正确获取行数据

                            // 阻止事件冒泡
                            var event = window.event || arguments.callee.caller.arguments[0];
                            if (event) event.stopPropagation();

                            // 调用输入框
                            InputCount(rowData);
                        });
                    }
                });

                // 加载初始数据
                loadData();
            }

            // 生成数据哈希用于比较数据变化
            function generateDataHash(data) {
                return JSON.stringify(data.map(item => ({
                    norm_code: item.norm_code,
                    quantity: item.quantity,
                    remark: item.remark,
                    conversions: item.conversions || []
                })));
            }

            // 检查是否有未保存的更改
            window.hasUnsavedChanges = function () {
                return hasUnsavedChanges;
            };

            // 更新保存状态显示
            function updateSaveStatus() {
                var $status = $('#save-status');
                if (hasUnsavedChanges) {
                    $status.show().find('.status-indicator')
                        .removeClass('status-saved')
                        .addClass('status-unsaved')
                        .next('span').text('未保存');
                } else {
                    $status.show().find('.status-indicator')
                        .removeClass('status-unsaved')
                        .addClass('status-saved')
                        .next('span').text('已保存');
                }
            }

            // 标记有未保存的更改
            function markAsUnsaved() {
                var currentHash = generateDataHash(tableData);
                hasUnsavedChanges = (currentHash !== originalDataHash);
                updateSaveStatus();
            }

            // 标记为已保存
            function markAsSaved() {
                originalDataHash = generateDataHash(tableData);
                hasUnsavedChanges = false;
                updateSaveStatus();
            }

            // 加载初始数据
            function loadData() {
                var loading = layer.load();

                http.get(API_CONFIG.ENDPOINTS.LOAD_LABOR, {
                    design_code: designCode,
                    design_type: designType
                }).then(function (res) {
                    layer.close(loading);

                    if (res.code === 0 && res.data && res.data.length > 0) {
                        tableData = res.data.map(function (item, index) {
                            // 确保conversions是一个数组
                            var conversions = (item.conversion && Array.isArray(item.conversion)) ? item.conversion : [];

                            return {
                                ...item,
                                _id: item.id || 'row_' + index + '_' + Date.now(),
                                norm_code: item.norm_item.norm_code,
                                norm_name: item.norm_item.norm_name,
                                norm_unit: item.norm_item.norm_unit,
                                quantity: Number(item.quantity) || 0,
                                norm_mechanic: Number(item.norm_item.norm_mechanic * item.norm_item.norm_ratio) || 0,
                                norm_general: Number(item.norm_item.norm_general * item.norm_item.norm_ratio) || 0,
                                mechanics: Number(item.norm_item.norm_mechanic * item.quantity * item.norm_item.norm_ratio) || 0,
                                generals: Number(item.norm_item.norm_general * item.quantity * item.norm_item.norm_ratio) || 0,
                                converted_mechanics: laborConvert(item.norm_item.norm_mechanic * item.norm_item.norm_ratio, item.quantity, conversions),
                                converted_generals: laborConvert(item.norm_item.norm_general * item.norm_item.norm_ratio, item.quantity, conversions),
                                remark: item.remark,
                                conversions: item.conversion // 确保conversions属性存在
                            };
                        });
                    } else {
                        tableData = [];
                    }

                    table.reload('table3a', {
                        data: tableData,
                        url: null
                    });

                    markAsSaved(); // 初始加载后标记为已保存

                }).catch(function (err) {
                    console.log(err.message);

                    layer.close(loading);
                    tableData = [];
                    table.reload('table3a', {
                        data: [],
                        url: null
                    });
                    layer.msg('数据加载失败', { icon: 2 });
                });
            }

            // 定额调整计算
            function laborConvert(normValue, quantity, conversions) {
                const numValue = Number(normValue);
                const numQuantity = Number(quantity);
                if (isNaN(numValue) || isNaN(numQuantity)) {
                    console.warn('laborConvert: 无效的数值参数', { normValue, quantity });
                    return 0;
                }
                if (!isFinite(numValue) || !isFinite(numQuantity)) {
                    console.warn('laborConvert: 数值超出范围', { numValue, numQuantity });
                    return 0;
                }
                const conversionsArray = Array.isArray(conversions) ? conversions : [];
                let result = numValue * numQuantity;
                conversionsArray.forEach(con => {
                    if (con && typeof con.rate_labor === 'number' && isFinite(con.rate_labor)) {
                        result *= con.rate_labor;
                    }
                });
                return Number(result);
            }

            // 绑定表格事件
            function bindTableEvents() {
                // 删除操作
                table.on('tool(table3a)', function (obj) {
                    if (obj.event === 'delete') {
                        layer.confirm('确定删除此条目？', function (index) {
                            var deleteIndex = tableData.findIndex(function (item) {
                                return item._id === obj.data._id;
                            });

                            if (deleteIndex !== -1) {
                                tableData.splice(deleteIndex, 1);

                                table.reload('table3a', {
                                    data: tableData,
                                    url: null
                                });

                                markAsUnsaved(); // 标记有未保存的更改
                                layer.msg('删除成功', { icon: 1 });
                            }

                            layer.close(index);
                        });
                    }
                });

                // 单元格编辑
                table.on('edit(table3a)', function (obj) {
                    var field = obj.field;
                    var value = obj.value;

                    var item = tableData.find(i => i._id === obj.data._id);
                    if (item) {
                        item[field] = field === 'quantity' || field === 'rate' ?
                            Number(value) || 0 : value;

                        if (field === 'quantity') {
                            // 确保conversions存在
                            var conversions = item.conversions && Array.isArray(item.conversions) ? item.conversions : [];

                            item.mechanics = Number((item.norm_mechanic * item.quantity).toFixed(2)) || 0;
                            item.generals = Number((item.norm_general * item.quantity).toFixed(2)) || 0;
                            item.converted_mechanics = laborConvert(item.norm_mechanic, item.quantity, conversions);
                            item.converted_generals = laborConvert(item.norm_general, item.quantity, conversions);

                            table.reload('table3a', {
                                data: tableData,
                                url: null
                            });
                        }

                        markAsUnsaved(); // 标记有未保存的更改
                    }
                });
            }

            // 全局添加函数
            window.handleNormSelect = function (data) {
                // 确保conversions属性存在
                var conversions = data.conversions && Array.isArray(data.conversions) ? data.conversions : [];

                var newItem = {
                    ...data,
                    _id: 'row_' + Date.now(),
                    quantity: parseFloat(data.quantity) || 0,
                    norm_mechanic: parseFloat(data.norm_mechanic) || 0,
                    norm_general: parseFloat(data.norm_general) || 0,
                    mechanics: Number((data.norm_mechanic * data.quantity).toFixed(2)) || 0,
                    generals: Number((data.norm_general * data.quantity).toFixed(2)) || 0,
                    converted_mechanics: laborConvert(data.norm_mechanic, data.quantity, conversions),
                    converted_generals: laborConvert(data.norm_general, data.quantity, conversions),
                    conversions: conversions, // 确保conversions属性存在
                    remark: data.remark || '',
                };

                tableData.push(newItem);

                table.reload('table3a', {
                    data: tableData,
                    url: null
                });

                markAsUnsaved(); // 标记有未保存的更改
                layer.msg('已添加: ' + data.norm_name, { icon: 1 });
            };

            // 保存数据函数（暴露给父窗口）
            window.saveData = function (callback) {
                var invalidItems = tableData.filter(function (item) {
                    return isNaN(item.quantity) || item.quantity <= 0;
                });

                if (invalidItems.length > 0) {
                    layer.msg('请检查数量输入，必须为大于0的数字', { icon: 2 });
                    if (typeof callback === 'function') callback(false);
                    return;
                }

                var loading = layer.load();
                var saveData = tableData.map(function (item) {
                    // 安全检查：确保conversions存在且是数组
                    var conversions = (item.conversions && Array.isArray(item.conversions)) ? item.conversions : [];
                    var conversionData = [];

                    // 安全地遍历conversions
                    conversions.forEach(function (con) {
                        conversionData.push({
                            nci_id: con.id ? parseInt(con.id) : 0,
                            lid: con.lid || '',
                        });
                    });

                    return {
                        lid: "",
                        design_code: designCode,
                        design_type: designType,
                        code: item.norm_code,
                        quantity: item.quantity,
                        remark: item.remark,
                        conversions: conversionData,
                        machines: item.machines || [],
                        instruments: item.instruments || [],
                    };
                });

                http.post(API_CONFIG.ENDPOINTS.SAVE_LABOR, {
                    design_code: designCode,
                    design_type: designType,
                    labor_table: saveData,
                }).then(function (res) {
                    layer.close(loading);
                    if (res.code === 0) {
                        layer.msg('保存成功', { icon: 1 });
                        markAsSaved(); // 标记为已保存

                        // 刷新父页面项目摘要数据
                        if (parent && parent.updateProjectData) {
                            parent.updateProjectData(designCode, designType);
                        }

                        if (typeof callback === 'function') callback(true);
                    } else {
                        layer.msg(res.msg || '保存失败，请重试', { icon: 2 });
                        if (typeof callback === 'function') callback(false);
                    }
                }).catch(function (err) {
                    layer.close(loading);
                    layer.msg('网络错误，保存失败', { icon: 2 });
                    if (typeof callback === 'function') callback(false);
                });
            };

            // 添加按钮
            $('#btn-add').click(function () {
                var openurl = '/common/norm_labor.html';
                bsm_utils.bsm_popup('双击选择人工定额', openurl, 2);
            });

            // 保存按钮点击事件
            $('#btn-save').click(function () {
                window.saveData(function (success) {
                    if (success) {
                        // 保存成功后的额外操作
                    }
                });
            });

            // URL参数获取
            function getUrlParam(name) {
                var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
                var r = window.location.search.substr(1).match(reg);
                return r ? decodeURIComponent(r[2]) : null;
            }

            // 编辑人工条目（本页为双击条目调用）
            function InputCount(rowData) {
                http.get(API_CONFIG.ENDPOINTS.GET_NORM_CONVERSION + '?normcode=' + rowData.norm_code)
                    .then(function (res) {
                        var options = res.data;

                        // 获取当前已选中的调整选项ID
                        var selectedOptionIds = [];
                        // 安全检查：确保rowData.conversions存在且是数组
                        if (rowData.conversions && Array.isArray(rowData.conversions)) {
                            selectedOptionIds = rowData.conversions.map(function (con) {
                                return con.id ? con.id.toString() : (con.nci_id ? con.nci_id.toString() : '');
                            }).filter(Boolean);
                        }

                        layer.open({
                            type: 1,
                            title: "定额：" + rowData.norm_name,
                            content: `
                            <div class="layui-form" style="padding:10px;">
                                <div class="layui-form-item">
                                    <!-- 数量输入框 -->
                                    <div class="layui-input-group" style="margin-bottom: 15px;">
                                        <div class="layui-input-prefix" style="width:80px;">设计数量</div>
                                        <input type="number" lay-affix="number" id="inputQuantity" min="0.001" step="0.001" lay-precision="3" class="layui-input" value="${rowData.quantity || ''}">
                                        <div class="layui-input-suffix" style="width:80px; text-align:left;">${rowData.norm_unit || '个'}</div>
                                    </div>
                                    
                                    <!-- 调整选项（根据是否有选项决定显示） -->
                                    ${options && options.length > 0 ? `
                                    <div class="layui-input-group" style="margin-bottom: 15px;">
                                        <div class="layui-input-prefix" style="width:80px;">调整选项</div>
                                        <div class="layui-input-block" style="margin-left: 90px; padding-top: 5px;">
                                            ${options.map(opt => {
                                const isChecked = selectedOptionIds.includes(opt.id.toString());
                                return `<input type="checkbox" name="optionSelect" value="${opt.id}" title="${opt.name}" lay-skin="primary" ${isChecked ? 'checked' : ''}>`;
                            }).join('')}
                                        </div>
                                    </div>`
                                    :
                                    `
                                    <div class="layui-form-item">
                                        <div class="layui-input-block" style="margin-left: 0;">
                                            <div class="layui-form-mid layui-word-aux">该项目无调整选项</div>
                                        </div>
                                    </div>`}
                                </div>

                                <!-- 备注文字输入框 -->
                                <div class="layui-form-item" style="margin-left:10px;margin-right:10px;">
                                    <textarea class="layui-textarea" placeholder="备注施工说明" style="margin-top: 10px;" id="inputRemark">${rowData.remark || ''}</textarea>
                                </div>
                            </div>`,
                            btn: ['确认', '取消'],
                            area: ['480px', '380px'],
                            success: function (layero, index) {
                                this.layero = layero;
                                layero.find('#inputQuantity').focus();
                                form.render(); // 重新渲染表单，确保复选框状态正确显示

                                $('#inputQuantity').on('keypress', function (e) {
                                    if (e.keyCode === 13) $('.layui-layer-btn0').click();
                                });
                            },
                            yes: function (index) {
                                var layero = this.layero;
                                var quantity = parseFloat($('#inputQuantity').val());
                                var selectedConversions = [];
                                var remark = $('#inputRemark').val();

                                if (isNaN(quantity) || quantity <= 0) {
                                    layer.msg('请输入有效的大于0的数字', { icon: 2 });
                                    $('#inputQuantity').focus();
                                    return false;
                                }

                                // 获取选中的调整选项
                                layero.find('input[name="optionSelect"]:checked').each(function () {
                                    var optionId = $(this).val();
                                    var selectedConversion = options.find(opt => opt.id == optionId);
                                    if (selectedConversion) {
                                        selectedConversions.push(selectedConversion);
                                    }
                                });

                                // 更新行数据
                                var rowIndex = tableData.findIndex(item => item._id === rowData._id);
                                if (rowIndex !== -1) {
                                    tableData[rowIndex].quantity = quantity;
                                    tableData[rowIndex].conversions = selectedConversions;
                                    tableData[rowIndex].remark = remark;

                                    // 重新计算相关值
                                    tableData[rowIndex].mechanics = Number((tableData[rowIndex].norm_mechanic * quantity).toFixed(2)) || 0;
                                    tableData[rowIndex].generals = Number((tableData[rowIndex].norm_general * quantity).toFixed(2)) || 0;
                                    tableData[rowIndex].converted_mechanics = laborConvert(tableData[rowIndex].norm_mechanic, quantity, selectedConversions);
                                    tableData[rowIndex].converted_generals = laborConvert(tableData[rowIndex].norm_general, quantity, selectedConversions);

                                    // 刷新表格
                                    table.reload('table3a', {
                                        data: tableData,
                                        url: null
                                    });

                                    markAsUnsaved(); // 标记有未保存的更改
                                    layer.msg('修改成功', { icon: 1 });
                                }

                                layer.close(index);
                            }
                        });
                    })
                    .catch(function (err) {
                        layer.msg('加载选项数据失败: ' + (err.message || err.msg), { icon: 2 });
                        console.error('API错误:', err);
                    });
            }

            // 设置表单只读
            function setFormReadonly(isReadonly) {
                var btnSave = document.getElementById('btn-save');
                var btnAdd = document.getElementById('btn-add');
                if (isReadonly) {
                    document.querySelectorAll('input, textarea, select').forEach(function (element) {
                        element.setAttribute('readonly', 'readonly'); // 对于input, textarea
                        element.setAttribute('disabled', 'disabled'); // 对于select, checkbox, radio等
                    });
                    btnAdd.setAttribute('disabled', 'disabled');
                    btnSave.className = 'layui-btn layui-btn-disabled';
                }
                form.render();

            }

            // 初始化执行
            initTable();

            // 添加页面离开前的提示
            window.addEventListener('beforeunload', function (e) {
                if (hasUnsavedChanges) {
                    var confirmationMessage = '您有未保存的更改，确定要离开吗？';
                    e.returnValue = confirmationMessage;
                    return confirmationMessage;
                }
            });
        });
    </script>
</body>

</html>